package com.corex.vinayak.views;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.classapp.login.LoginBeanMobile;
import com.corex.pinmethods.SetPinActivity;
import com.corex.responsebean.LoginResponse;
import com.corex.staticclasses.PrivateData;
import com.corex.staticclasses.StaticData;
import com.corex.utils.Constants;
import com.corex.vinayak.LoginSuccessActivity;
import com.corex.vinayak.R;
import com.corex.vinayak.VinayakActivity;
import com.corex.webservice.LoginService;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class LoginScreen extends Fragment {
	private final static String SENDER_ID = "485938436404";
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	int i=0;
	Button login_btn;
	EditText login_name;
	EditText login_pass;
	ProgressDialog progressDialog;
	String googleId;

	OnClickListener textErrorListner = new OnClickListener() {

		@Override
		public void onClick(View v) {
			login_name.setError(null);
			login_pass.setError(null);
			
		}
	};

	public LoginScreen() {
	}

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode== Activity.RESULT_OK) {
            if (data.getBooleanExtra(Constants.IS_PIN_CORRECT, false)) {
                loginAction(true);
            } else {
                getActivity().finish();
            }
        }else{
            getActivity().finish();
        }
    }

    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View rootView = inflater.inflate(R.layout.splashscreen, container,
				false);
		progressDialog = new ProgressDialog(rootView.getContext());
		PrivateData privateData = new PrivateData(getActivity());
		if(null != privateData.getLoginBeanMobile()){
            Intent intent = new Intent(getActivity(),SetPinActivity.class);
            intent.putExtra(Constants.PIN_SCREEN_TYPE, "CheckPin");
            startActivityForResult(intent,Constants.PIN_CHECK_REQ_CODE);
		}else{
			rootView = inflater.inflate(R.layout.fragment_vinayak, container,
					false);
			login_btn = (Button) rootView.findViewById(R.id.login_btn);
			login_name = (EditText) rootView.findViewById(R.id.login_username);
			login_pass = (EditText) rootView.findViewById(R.id.login_password);

		login_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				if (login_name.getText().toString().trim().length() == 0) {
					login_name.setError("Username can not be blank");
				} else if (login_pass.getText().toString().trim().length() == 0) {
					login_pass.setError("Password can not be blank");
				} else {
					loginAction(false);
				}
				}
		});
		}

		return rootView;
	}
	
	public boolean checkPlayService(){
		int isServiceAvail = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getApplicationContext());
		if (isServiceAvail != ConnectionResult.SUCCESS) {
			 if (GooglePlayServicesUtil.isUserRecoverableError(isServiceAvail)) {
		            GooglePlayServicesUtil.getErrorDialog(isServiceAvail, getActivity(),
		                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
		        } else {
		            Log.i("TAG", "This device is not supported.");
		            //finish();
		        }
			 return false;
		}else{
			return true;
		}
	}
	
	@SuppressWarnings({  "unchecked", "rawtypes" })
	private String registerInBackground() {
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(getActivity().getApplicationContext());
		String msg = null;
		try {
			msg = gcm.register(SENDER_ID);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return msg;
	}

	public void loginAction(final boolean isPinPassed){

		final Thread thread = new Thread() {
			String msg = "";
			public void run() {
				try {
					getActivity().runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressDialog.setMessage("Connecting....");
							progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
							progressDialog.setIndeterminate(true);
							progressDialog.setCancelable(false);
							progressDialog.show();
							progressDialog.setMessage("Registering for google id");
							}
					});

				} catch (Exception e) {
					e.printStackTrace();
				}
				
				if (checkPlayService()) {
					msg = registerInBackground();
				}
				
				if(null!=msg){
					googleId = msg;
				}
				 
			};
		};
		
		thread.start();
	
		
	Thread loginThread = new Thread(new Runnable() {
		
		@Override
		public void run() {
			
			try {
				thread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					progressDialog.setMessage("Login in");
				}
			});
			
			if(null==googleId || "".equals(googleId)){
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						progressDialog.setMessage("Google Id not found Exiting...");
					}
				});

                try {
                    Thread.sleep(2 * 1000);
                }catch(Exception e){
                    e.printStackTrace();
                }

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        getActivity().finish();
                    }
                });
			}else{
			LoginService loginService = new LoginService();
			
			PrivateData privateData = new PrivateData(getActivity());
			final LoginResponse loginResp;

                TelephonyManager telephonyManager = (TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                String deviceId = telephonyManager.getDeviceId();

            if(null==privateData.getLoginBeanMobile()){
				loginResp = loginService.executeLogin(login_name.getText().toString(),login_pass.getText().toString(),googleId,deviceId);
			}else{
				loginResp = loginService.executeLogin(privateData.getLoginBeanMobile().getUsername(),privateData.getLoginBeanMobile().getPassword(),googleId,deviceId);
			}
			getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					progressDialog.dismiss();
					
					if(null!=loginResp && "000".equals(loginResp.getResultBean().getCode()) && (null!=loginResp.getUserBean() && null!=loginResp.getUserBean().getRole() && loginResp.getUserBean().getRole() == 3)){
						StaticData.loginResponse = loginResp;

						PrivateData privateData = new PrivateData(getActivity());
						privateData.setLoginBeanMobile(loginResp.getUserBean().getLoginBean());
						
						Intent intent = null;
                        if(isPinPassed){
                            Intent intent1 = new Intent(getActivity(),com.corex.navigationdrawer.LoginSuccessActivity.class);
                            startActivity(intent1);
                            getActivity().finish();
                        }

                        if(null == privateData.getPin()){
							intent = new Intent(getActivity(),SetPinActivity.class);
                            startActivity(intent);
                            getActivity().finish();
                        }else{
						/*	intent = new Intent(getActivity(),SetPinActivity.class);
							intent.putExtra(Constants.PIN_SCREEN_TYPE, "CheckPin");
							*/
						}

					}else if(null!=loginResp && "401".equals(loginResp.getResultBean().getCode()) && null == login_name){
                        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());

                        alert.setTitle("Password Changed");
                        alert.setMessage("Your password might changed, Please reenter password");

                        // Set an EditText view to get user input
                        final EditText input = new EditText(getActivity());
                        alert.setView(input);

                        alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                String password = input.getText().toString();
                                PrivateData privateData = new PrivateData(getActivity());
                                LoginBeanMobile loginBeanMobile = privateData.getLoginBeanMobile();
                                loginBeanMobile.setPassword(password);
                                privateData.setLoginBeanMobile(loginBeanMobile);
                                loginAction(true);
                            }
                        });

                        alert.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                getActivity().finish();
                            }
                        });

                        alert.setNeutralButton("Logout",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                PrivateData privateData1 = new PrivateData(getActivity());
                                privateData1.cleanPreference();
                                getActivity().finish();
                            }
                        });
                        alert.show();
					}else{
                        login_name.setError("Wrong username or Password");
                    }
				}
			});
				
		}
		}
	});
	
	loginThread.start();
	
	}
}
